package com.tengfei.main.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tengfei.common.core.domain.PageQuery;
import com.tengfei.common.core.page.TableDataInfo;
import com.tengfei.common.exception.ServiceException;
import com.tengfei.common.utils.DateUtils;
import com.tengfei.common.utils.StringUtils;
import com.tengfei.main.course.config.AliyunConfig;
import com.tengfei.main.course.config.FfmPegConfig;
import com.tengfei.main.course.domain.ChapterVideo;
import com.tengfei.main.course.domain.Video;
import com.tengfei.main.course.domain.bo.VideoBo;
import com.tengfei.main.course.domain.vo.VideoVo;
import com.tengfei.main.course.mapper.ChapterVideoMapper;
import com.tengfei.main.course.mapper.VideoMapper;
import com.tengfei.main.course.service.IVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import static com.tengfei.common.utils.file.MimeTypeUtils.VIDEO_TYPE;

/**
 * 视频Service业务层处理
 *
 * @author tengfei
 * @date 2022-07-26
 */
@Slf4j
@Service
public class VideoServiceImpl implements IVideoService {

    @Resource
    private VideoMapper baseMapper;
    @Resource
    private FfmPegConfig ffmPegConfig;
    @Resource
    private FfmpegExec ffmpegExec;
    @Resource
    private AliyunConfig aliyunConfig;
    @Resource
    private ChapterVideoMapper chapterVideoMapper;


    /**
     * 查询视频
     */
    @Override
    public VideoVo queryById(Long videoId) {
        return baseMapper.selectVoById(videoId);
    }

    /**
     * 查询视频列表
     */
    @Override
    public TableDataInfo<VideoVo> queryPageList(VideoBo bo, PageQuery pageQuery) {
        Page<VideoVo> result = baseMapper.selectVoPage(pageQuery.build(), new LambdaQueryWrapper<Video>()
                .like(StringUtils.isNotBlank(bo.getVideoName()), Video::getVideoName, bo.getVideoName())
                .orderByDesc(Video::getUpdateTime));
        return TableDataInfo.build(result);
    }

    /**
     * 修改视频
     */
    @Override
    public Boolean updateByBo(VideoBo bo) {
        if (ObjectUtil.isNull(bo.getVideoId())) {
            throw new ServiceException("视频id为空");
        }
        Video update = BeanUtil.toBean(bo, Video.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除视频
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        // 查询视频是否被引用
        ids.forEach(id -> {
            Long count = chapterVideoMapper.selectCount(new QueryWrapper<ChapterVideo>()
                    .eq("video_id", id));
            if (count.intValue() > 0) {
                throw new ServiceException("视频被课程章节引用,不可删除");
            }

        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 上传视频
     *
     * @param file
     * @return
     */
    @Override
    public VideoVo uploadVideo(MultipartFile file) {

        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传视频不能为空");
        }

        // 获取文件拓展名
        String extName = FileNameUtil.extName(file.getOriginalFilename());
        boolean isVideo = false;
        for (String s : VIDEO_TYPE) {
            if (extName.equalsIgnoreCase(s)) {
                isVideo = true;
                break;
            }
        }
        if (!isVideo) {
            throw new ServiceException("非mp4/mkv/avi视频文件");
        }

        String newFileName = UUID.randomUUID().toString();
        StringBuilder sb = new StringBuilder(ffmPegConfig.getTemp());
        sb.append(newFileName);
        sb.append("/");
        // 判断文件夹是否存在
        File fold = new File(sb.toString());
        if (!fold.exists()) {
            fold.mkdirs();
        }
        sb.append(newFileName);
        sb.append(".");
        sb.append(extName);

        // 文件拷贝到临时空间
        String filePath = sb.toString();
        try (
                BufferedInputStream bis = (BufferedInputStream) file.getInputStream();
                FileOutputStream fos = new FileOutputStream(filePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {
            byte b[] = new byte[102400];
            while (bis.read(b, 0, b.length) != -1) {
                bos.write(b, 0, b.length);
            }
        } catch (Exception e) {
            throw new ServiceException("文件上传失败");
        }


        // 将数据保存进数据库
        // 获取视频大小
        long size = file.getSize();
        Video video = new Video();
        video.setVideoSize(size);
        video.setVideoStatus(0);
        // 计算出路径地址
        String outPath = new StringBuilder(DateUtils.datePath())
                .append("/")
                .append(newFileName)
                .append("/")
                .toString();
        String url = new StringBuilder(aliyunConfig.getUrlPrefix())
                .append(aliyunConfig.getRootPath())
                .append("/video/")
                .append(outPath)
                .append(newFileName)
                .append(".m3u8")
                .toString();
        video.setVideoUrl(url);
        video.setVideoName(FileNameUtil.mainName(file.getOriginalFilename()));

        boolean res = baseMapper.insert(video) > 0;
        if (!res) {
            throw new ServiceException("文件上传失败");
        }
        VideoVo videoVo = new VideoVo();
        videoVo.setVideoId(video.getVideoId());
        videoVo.setVideoName(video.getVideoUrl());

        // 异步视频转m3u8，转换成功后异步上传oss
//        convertM3U8.processM3U8(filePath, outPath, newFileName, video.getVideoId());
        ffmpegExec.video2m3u8(filePath, outPath, newFileName, video.getVideoId());
        return videoVo;
    }

    /**
     * 根据id查询视频时长
     *
     * @param videoId
     * @return
     */
    @Override
    public Integer queryDurationById(Long videoId) {
        Video video = baseMapper.selectById(videoId);
        if (ObjectUtil.isNull(video)) {
            return null;
        }
        return video.getVideoDuration();
    }
}
